package com.itheima.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.netty.MyWebSocketHandler;
import com.rabbitmq.client.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;

import java.util.HashMap;

//监听消息订阅

public class SysNoticeListener implements ChannelAwareMessageListener {
    private static ObjectMapper MAPPER = new ObjectMapper();
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        //获取队列名称
        String consumerQueue = message.getMessageProperties().getConsumerQueue();
        String substring = consumerQueue.substring(consumerQueue.lastIndexOf("_") + 1);
        //根据用户id过去连接
        io.netty.channel.Channel channel1 = MyWebSocketHandler.userChannelMap.get(substring);
        if(channel1!=null){
            //用户在线就把消息队列接受到的消息写给用户
            HashMap hashMap = new HashMap();
            hashMap.put("sysNoticeCount", 1);
            Result result = new Result(true, StatusCode.OK, "查询成功", hashMap);
            channel1.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(result)));

        }
    }
}
